# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: script_4.py
@time: 2024/10/30 21:03 
@desc: 

"""
from scripts.base_script import BaseScript
from sdk.utils.util_class import PathParser


class Solution(BaseScript):
    """

    """

    def __init__(self):
        super(Solution, self).__init__()
        self.desc = f"script_1473判卷"
        print(self.desc)
        self.q_map = {
            "1": "视频无问题",
            "2": "1.字幕影响主画面（仅横屏）",
            "3": "2.字幕前后不在一个水平线",
            "4": "3.字幕遮挡不完全",
            "5": "4.字幕擦除不干净",
            "6": "5.字幕重复/重叠/串行",
            "7": "6.无关/生硬拼接",
            "8": "7.音、视频有硬伤",
            "9": "8.音、视频表述不完整/被截断",
            "10": "9.内容画面杂乱",
            "11": "10.低俗色情",
            "12": "11.音画不一致",
            "13": "12.内容引起不适",
            "14": "13.内容中有站外联系方式",
            "15": "14.视频画幅不和谐",
            "16": "15.背景音乐紧张",
            "17": "16.文品一致性",
            "18": "17.通顺度",
            "19": "18.出现利益点、价格信息",
            "20": "19.出现时效信息",
            "21": "20.生成其他文案",
            "22": "无",
        }
        self.single = False

    def get_map_from_origin(self, file, sheet):
        """

        :param file:
        :return:
        """
        map = {}
        for args in self.excel.read_yield_by_pandas(file, sheets=[sheet]):
            id = self.get_one_from_yield_args(args, "序号")
            url = self.get_one_from_yield_args(args, "视频链接")
            desc = self.get_one_from_yield_args(args, "脚本")
            tag1 = str(self.get_one_from_yield_args(args, "标签1"))
            tag2 = str(self.get_one_from_yield_args(args, "标签2"))
            tag3 = str(self.get_one_from_yield_args(args, "标签3"))
            tag2 = tag2 if tag2 != "nan" else "无"
            tag1 = tag1 if tag1 != "nan" else "无"
            tag3 = tag3 if tag3 != "nan" else "无"
            if map.get(id) is None:
                map[str(id)] = [url, desc, tag3, tag2, tag1]
            else:
                print(f"重复：{id}--{args['num']}")
        return map

    def check_answer(self, input_file, stand_file, sheet):
        """

        :param input_file:
        :param stand_file:
        :param sheet:
        :return:
        """
        total_map = {}
        error_map = {}
        right_map = {}
        stand_map = self.get_map_from_origin(stand_file, sheet)
        self.all_nums = len(stand_map)
        file_obj = PathParser(input_file)
        replay_nums = 0
        for args in self.csv.read_yield_csv(input_file):
            print("args", args)
            answer = self.json.loads(self.get_one_from_yield_args(args, "answer"))
            replay_nums += 1
            base = ""
            phone = ""
            alliance = ""
            name = ""
            answer_args = answer["questions"][0]["answer"]
            for key, value in answer_args.items():
                if key == "base":
                    base = value
                elif key == "phone":
                    phone = value
                elif key == "alliance":
                    alliance = value
                elif key == "name":
                    name = value

            answer_list = []
            error_recode = []

            right_nums = 0
            # print("self.all_nums", self.all_nums)
            for i in range(1, self.all_nums + 1):
                i = str(i)
                if error_map.get(i) is None:
                    error_map[i] = {}

                if right_map.get(i) is None:
                    right_map[i] = {}

                if stand_map.get(i) is not None:
                    # 单独处理 sheet 0829
                    if sheet in ("0829", "0830", "0831", "练习3"):
                        # 匹配 sheet 0829
                        new_key_list = [f"label_1_0_{int(i) - 1}"]
                    else:
                        # 原始
                        new_key_list = [f"label_1_1_0_{int(i) - 1}"]

                    use_answer_all = []
                    stand_answer_all = []
                    for ind, j in enumerate(new_key_list, 1):
                        user_answer = self.q_map.get(answer_args.get(j).get("value"))
                        stand_answer = [i for i in stand_map.get(i)[-3:] if i != "无"]
                        use_answer_all.append(user_answer)
                        stand_answer.reverse()
                        stand_answer_all.extend(stand_answer)

                        for j in stand_answer:
                            if right_map[i].get(j) is None:
                                right_map[i].update({j: 0})

                        if user_answer in stand_answer:
                            right_nums += 1

                            if right_map[i].get(user_answer) is None:
                                right_map[i].update({user_answer: 1})
                            else:
                                right_map[i][user_answer] = right_map[i][user_answer] + 1
                        else:
                            error_recode.append(i)
                            if total_map.get(i) is None:
                                total_map[i] = 1
                            else:
                                total_map[i] = total_map[i] + 1
                            new_use_answer_all = "".join(use_answer_all)
                            if error_map[i].get(new_use_answer_all) is None:
                                error_map[i].update({new_use_answer_all: 1})
                            else:
                                error_map[i][new_use_answer_all] = error_map[i][new_use_answer_all] + 1
                    answer_list.append(["\n".join(use_answer_all), "\n".join(stand_answer_all)])

                else:
                    print(f"原始卷中不存在：{i}")

            right_rate = round(right_nums * 100 / self.all_nums, 2)
            print(f"正确率：{right_rate}")
            _temp = args["line"][:4]
            _temp += [name]
            _temp.extend([f"{base}", phone, alliance, f"{right_rate} %", "\n".join(error_recode)])
            for i in answer_list:
                _temp.extend(i)
            self.success_lis.append(_temp)

        _hd = []
        for i in range(1, self.all_nums + 1):
            _hd.extend([f"用户答案{i}", f"正确答案{i}"])

        new_hd = ["项目ID",
                  "场次ID",
                  "场次名称",
                  "题目ID",
                  "百度账户名",
                  "base", "phone", "alliance",
                  "正确率",
                  "错误题号"
                  ] + _hd

        csv_name = f"result_{self.desc}_{self.time.get_normal_date()}.csv"
        self.csv.write_to_csv(file=self.folder.merge_path([self.tmp_folder, csv_name]), data=self.success_lis,
                              headers=new_hd, encoding="gbk")
        self.success_lis = []

        for q_id, value in error_map.items():
            right_rate2 = f"{round((replay_nums - total_map.get(q_id, 0)) / replay_nums * 100, 2)} %"
            right_answer = stand_map.get(q_id)[-3:]
            right_answer.reverse()
            tmp = [q_id, total_map.get(q_id, 0), replay_nums, right_rate2]

            for i in right_answer:
                tmp.extend([i, right_map.get(q_id).get(i)])

            for error_desc, error_times in dict(
                    sorted(value.items(), key=lambda item: item[1], reverse=True)).items():
                tmp.extend([error_desc, error_times])
            tmp = [str(i) for i in tmp]

            __header = []
            for i in range(1, 4):
                __header.extend([f"正确答案{i}", f"正确答案{i}出现次数"])

            _header = ["题号", "错误次数", "答题次数", "正确率"] + __header

            for i in range(1, int((len(tmp) - 10) / 2) + 1):
                _header.extend([f"错误答案{i}", f"错误答案{i}出现次数"])

            self.error_lis.append(_header)
            self.error_lis.append(tmp)

        err_name = f"result_{self.desc}_{self.time.get_normal_date()}.txt"
        self.save_result(self.folder.merge_path([self.tmp_folder, err_name]), self.error_lis)
        self.error_lis = []

        self.zip.zip_files(self.tmp_folder, self.zip_file)
        self.folder.remove(folder=self.tmp_folder)
        return self.zip_name

    def process(self, data):
        """

        :return:
        """

        data["Desc"] = self.desc
        self.check_keys(data, ["input_file", "stand_file", "sheet"])
        input_file = self.tmp_upload_path + data["input_file"]
        stand_file = self.tmp_upload_path + data["stand_file"]
        # # 本地测试使用
        # input_file = data["input_file"]
        # stand_file = data["stand_file"]

        sheet = data["sheet"]
        download_file = ""
        download_file = self.check_answer(input_file, stand_file, sheet)
        download_file = download_file.replace('\\', '/')
        data["ScriptResults"] = download_file

        return data



if __name__ == '__main__':
    s = Solution()
    base_path = r"C:\Users\JHC\Desktop\dest\celery_test\tmp\uploads\\"
    data = {
        "input_file": base_path+r"f3bfb3a1-da0a-4d85-86b3-db83ecad7b22_考试结果-20241031113130.csv",
        "stand_file": base_path+r"27ad65ed-5590-4439-969a-3e04980032b8_AIGC.xlsx",
        "sheet": "准入30题",
    }
    s.process(data)
    """
    http://127.0.0.1/add?script_id=1556&input_file=22757ab5-0c40-4368-8fa1-26463dd02901_20241030181619.csv&stand_file=8d2e5221-57dc-40dc-be84-f27ffba4e0dd_AIGC.xlsx&sheet=准入30题
    
    """
